import { exportQuantityExcelApi, getOverdueUserList } from '@/services/api';
import { filterEmptyValues } from '@/utils/common';
import { FileSearchOutlined } from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Button, Tag, message } from 'antd';
import { isEqual } from 'lodash';
import React, { useRef, useState } from 'react';
import { USER_COMMON_COLUMNS } from '../../common';
import MapModal from '../Modal/MapModal';

const Overdue: React.FC = () => {
  const actionRef = useRef<ActionType>();

  /* 是否打开地图弹窗 */
  const [clientDrawerParams, setclientDrawerParams] = useState<{
    open: boolean;
    info: any;
  }>({
    open: false,
    info: '',
  });

  const { loading: exportLoading, runAsync } = useRequest(
    async (_parames) => {
      return await exportQuantityExcelApi({
        ..._parames,
      });
    },
    {
      manual: true,
    },
  );

  const columns: any = [
    ...USER_COMMON_COLUMNS,
    {
      title: '逾期天数大于天数',
      dataIndex: 'overdue_days__gte',
      valueType: 'digit',
      hideInTable: true,
    },
    {
      title: '逾期天数小数天数',
      dataIndex: 'overdue_days__lte',
      valueType: 'digit',
      hideInTable: true,
    },
    {
      title: '商户名称',
      // dataIndex: 'mpuser',
      dataIndex: ['mpuser','name'],
      hideInSearch: true,
    },
    {
      title: '用户姓名',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '用户号码',
      dataIndex: 'mobile',
      hideInSearch: true,
    },
    {
      title: '绑定电池',
      dataIndex: 'binding_batteries',
      hideInSearch: true,
      render: (text: any, record: any) => {
        return (
          <Tag color="blue" bordered={false}>
            {text}
          </Tag>
        );
      },
      width: 200,
    },
    {
      title: '逾期天数',
      dataIndex: 'overdue_days',
      hideInSearch: true,
    },
    {
      title: '到期时间',
      dataIndex: 'expiration_time',
      hideInSearch: true,
      valueType: 'date',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 80,
      render: (text: any, record: any) => [
        <a
          key="editable"
          onClick={() => {
            setclientDrawerParams({
              open: true,
              info: record,
            });
          }}
        >
          查询定位
        </a>,
      ],
    },
  ];

  const formRef = useRef<any>();

  return (
    <>
      <ProTable
        formRef={formRef}
        bordered
        columns={columns}
        actionRef={actionRef}
        cardBordered
        scroll={{ x: 1300 }}
        request={async (_parame) => {
          const { pageSize, current, ...ret } = _parame;
          const { data } = await getOverdueUserList({
            page: current,
            size: pageSize,
            filters: JSON.stringify({
              ...filterEmptyValues(ret),
            }),
          });
          return {
            data: data?.list ?? [],
            success: true,
            total: data?.count,
          };
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          defaultPageSize: 10,
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <Button
            loading={exportLoading}
            key="button"
            icon={<FileSearchOutlined />}
            onClick={async () => {
              /* 获取表格搜索框信息 */

              let _faileName: string = '逾期用户清单';
              let _header: any = [
                '商户名称',
                '用户姓名	',
                '用户号码',
                '绑定电池',
                '逾期天数',
                '到期时间',
              ];

              try {
                await runAsync({
                  filename: _faileName,
                  header: _header,
                  fields: [
                    'merchant',
                    'name',
                    'mobile',
                    'binding_batteries',
                    'overdue_days',
                    'expiration_time',
                  ],
                  table: 'journal_bindinglog',
                  filter: {
                    ...filterEmptyValues(formRef.current.getFieldsValue()),
                    merchant:
                      formRef.current.getFieldsValue()?.merchant__contains,
                    overdue_days_gt: 0
                  },
                });

                message.success(`文件${_faileName}导出成功`);
              } catch (error) {}
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
      />

      {clientDrawerParams.open && (
        <MapModal
          open={clientDrawerParams.open}
          onCancel={() => {
            setclientDrawerParams({
              open: false,
              info: '',
            });
            actionRef.current?.reload();
          }}
          info={clientDrawerParams.info}
        ></MapModal>
      )}
    </>
  );
};

export default React.memo(Overdue, (prev, next) => isEqual(prev, next));
